package com.ks.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ks.core.base.OperationContext;
import com.ks.core.constant.Const;
import com.ks.core.dto.SearchCriteriaBase;
import com.ks.core.exception.GunsException;
import com.ks.core.util.JsonUtil;
import com.ks.core.util.ToolUtil;
import com.ks.user.controller.dto.TemplateFrameRequest;
import com.ks.user.dao.TemplateFrameMapper;
import com.ks.user.entity.MicroApp;
import com.ks.user.entity.OrgTenant;
import com.ks.user.entity.TemplateFrame;
import com.ks.user.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 模板模块-小程序模板信息表 服务实现类
 * </p>
 *
 * @author kingdee123
 * @since 2020-12-09
 */
@Service
public class TemplateFrameServiceImpl extends _ServiceBase<TemplateFrameMapper, TemplateFrame> implements ITemplateFrameService {

    @Resource
    TemplateFrameMapper templateFrameMapper;

    @Resource
    private IWxAuthorService wxAuthorService;

    @Resource
    private IMicroAppService iMicroAppService;
    @Resource
    private IOrgTenantService orgTenantService;
    @Resource
    private IMemberVisitService visitService;


    @Override
    public TemplateFrame getTemplateFrameInfo(int id) {
        TemplateFrame templateFrame = templateFrameMapper.selectById(id);
        if (ToolUtil.isNotEmpty(templateFrame)) {
            return templateFrame;
        } else {
            throw new GunsException("模板Id不正确，未查找到该模板数据");
        }
    }

    @Override
    public Map<String, Object> getHomeIndex(String appId, String openId, Integer secret) {
        MicroApp microAppInfo = iMicroAppService.getMicroAppInfo(appId);
        if (ToolUtil.isEmpty(microAppInfo)){
            throw new GunsException("当前小程序没有授权租户");
        }
        EntityWrapper<TemplateFrame> wrapper = new EntityWrapper<>();
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setSMicroAppID(appId);
        templateFrame.setTenantID(microAppInfo.getTenantID());
        templateFrame.setSActive(Const.DEL_FLAG_DEL);
        wrapper.setEntity(templateFrame);
        List<TemplateFrame> templateFrames = templateFrameMapper.selectList(wrapper);
        if (templateFrames.size() < 1) {
            throw new GunsException("没有对应的首页");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", templateFrames.get(0).getIFrameContent());
        map.put("tenantId",templateFrames.get(0).getTenantID());
        visitService.addMemberVisit(appId,openId,templateFrames.get(0).getTenantID());
        return map;
    }

    @Override
    public Map<String, Object> getMouldIndex(OperationContext context, SearchCriteriaBase searchCriteriaBase) {
        //ArrayList<SearchCriteriaBase.matchField> fields = searchCriteriaBase.getFields();
        EntityWrapper<TemplateFrame> wrapper = new EntityWrapper<>();
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setTenantID(context.getTenantId().intValue());
        templateFrame.setCType("TENANT");
        templateFrame.setDelMark(Const.DEL_FLAG_NORMAL);
        wrapper.setEntity(templateFrame);
        Page limit = new Page(searchCriteriaBase.getPageIndex(), searchCriteriaBase.getLimit());
        List<TemplateFrame> templateFrames = templateFrameMapper.selectPage(limit, wrapper);
        Map<String, Object> resultMap = this.isResultMap(templateFrames, searchCriteriaBase);
        return resultMap;
    }

    @Override
    public Map<String, Object> getSysMouldIndex(OperationContext context, SearchCriteriaBase searchCriteriaBase) {
        EntityWrapper<TemplateFrame> wrapper = new EntityWrapper<>();
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setDelMark(Const.DEL_FLAG_NORMAL);
        ArrayList<SearchCriteriaBase.matchField> fields = searchCriteriaBase.getFields();
        if (ToolUtil.isNotEmpty(fields)) {
            for (SearchCriteriaBase.matchField field : fields) {
                if ("iName".equals(field.getName())) {
                    templateFrame.setIName((field.getValue()));
                }
                if ("tenantID".equals(field.getName())) {
                    templateFrame.setTenantID(Integer.valueOf(field.getValue()));
                }
            }
        }
        ArrayList<SearchCriteriaBase.StateField> states = searchCriteriaBase.getStates();
        if (ToolUtil.isNotEmpty(states)) {
            for (SearchCriteriaBase.StateField state : states) {
                if ("sActive".equals(state.getName())) {
                    templateFrame.setSActive(Integer.valueOf(state.getValue()));
                }
                if ("cType".equals(state.getName())) {
                    templateFrame.setCType((state.getValue()));
                }
            }
        }
        wrapper.setEntity(templateFrame);
        if (ToolUtil.isNotEmpty(searchCriteriaBase.getStartTime())) {
            wrapper.and("DATE_FORMAT( createTime, '%Y-%m-%d' ) >=" + "'" + searchCriteriaBase.getStartTime() + "'");
            wrapper.and("DATE_FORMAT( createTime, '%Y-%m-%d' ) <=  " + "'" + searchCriteriaBase.getEndTime() + "'");
        }
        List<TemplateFrame> templateFrames = templateFrameMapper.selectList(wrapper);
        if (ToolUtil.isNotEmpty(templateFrames)) {
            for (TemplateFrame frame : templateFrames) {
                if (ToolUtil.isNotEmpty(frame.getTenantID()) && frame.getTenantID() > 0) {
                    OrgTenant orgTenant = orgTenantService.selectById(frame.getTenantID());
                    if (ToolUtil.isNotEmpty(orgTenant)) {
                        frame.setTenantName(orgTenant.getIName());
                    }
                }

            }
        }
        Map<String, Object> map = this.isResultMap(templateFrames, searchCriteriaBase);
        return map;
    }

    @Override
    public Map<String, Object> getSysMouldIndexList(OperationContext context, SearchCriteriaBase searchCriteriaBase) {
        EntityWrapper<TemplateFrame> wrapper = new EntityWrapper<>();
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setDelMark(Const.DEL_FLAG_NORMAL);
        templateFrame.setCType("SYS");
        ArrayList<SearchCriteriaBase.matchField> fields = searchCriteriaBase.getFields();
        if (ToolUtil.isNotEmpty(fields)) {
            for (SearchCriteriaBase.matchField field : fields) {
                if ("iName".equals(field.getName())) {
                    templateFrame.setIName((field.getValue()));
                }
            }
        }
        ArrayList<SearchCriteriaBase.StateField> states = searchCriteriaBase.getStates();
        if (ToolUtil.isNotEmpty(states)) {
            for (SearchCriteriaBase.StateField state : states) {
                if ("sActive".equals(state.getName())) {
                    templateFrame.setSActive(Integer.valueOf(state.getValue()));
                }
            }
        }else {
            templateFrame.setSActive(Const.DEL_FLAG_DEL);
        }
        wrapper.setEntity(templateFrame);
        List<TemplateFrame> templateFrames = templateFrameMapper.selectList(wrapper);
        Map<String, Object> map = this.isResultMap(templateFrames, searchCriteriaBase);
        return map;
    }

    @Override
    public int isActive(OperationContext context, int id, int state) {
        TemplateFrame temp = templateFrameMapper.selectById(id);
        if (ToolUtil.isEmpty(temp)) {
            throw new GunsException("没有该模板");
        }
        temp.setSActive(state);
        Integer code = templateFrameMapper.updateById(temp);


        //       Integer i = templateFrameMapper.update();
        return code;
    }

    @Override
    public int delete(OperationContext context, int id) {
        TemplateFrame temp = templateFrameMapper.selectById(id);
        if (ToolUtil.isEmpty(temp)) {
            throw new GunsException("没有该模板");
        }
        temp.setDelMark(Const.DEL_FLAG_DEL);
        Integer code = templateFrameMapper.updateById(temp);
        return code;
    }

    @Override
    public int add(OperationContext context, TemplateFrame templateFrame) {
        Integer code = templateFrameMapper.insert(templateFrame);
        return code;
    }

    @Override
    public int update(OperationContext context, TemplateFrame templateFrame) {
        TemplateFrame temp = templateFrameMapper.selectById(templateFrame.getId());
        if (ToolUtil.isEmpty(temp)) {
            throw new GunsException("没有该模板");
        }
        Integer code = templateFrameMapper.updateById(templateFrame);
        return code;
    }

    @Override
    public int addTenantModel(OperationContext context, TemplateFrameRequest templateFrameRequest) {
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setSTemplateBase(templateFrameRequest.getId());
        templateFrame.setTenantID(context.getTenantId().intValue());
        templateFrame.setDelMark(Const.DEL_FLAG_NORMAL);
        templateFrame = templateFrameMapper.selectOne(templateFrame);
        if (ToolUtil.isNotEmpty(templateFrame)) {
            throw new GunsException("请勿重复添加!");
        }

        templateFrame = templateFrameMapper.selectById(templateFrameRequest.getId());
        templateFrame.setSTemplateBase(templateFrameRequest.getId());
        templateFrame.setTenantID(context.getTenantId().intValue());
        templateFrame.setOrgID(context.getOrgId().intValue());
        templateFrame.setOrgSubID(context.getOrgSubId().intValue());
        templateFrame.setSActive(Const.DEL_FLAG_NORMAL);
        templateFrame.setCType("TENANT");
        templateFrame.setDataType("TENANT");

        Integer i = templateFrameMapper.insert(templateFrame);
        return i;
    }

    @Override
    public int deleteTenantModel(OperationContext context, TemplateFrameRequest templateFrameRequest) {
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setId(templateFrameRequest.getId());

        templateFrame = templateFrameMapper.selectOne(templateFrame);

        if (templateFrame.getDataType().equals("SYS")) {
            throw new GunsException("系统模板无法删除");
        }
        if (templateFrame.getSActive() == 1) {
            throw new GunsException("已上线的模板无法删除");
        }
        templateFrame.setDelMark(Const.DEL_FLAG_DEL);
        Integer i = templateFrameMapper.updateById(templateFrame);
        return i;
    }

    @Override
    public int TenantEnableTemplate(OperationContext context, int id) {
        EntityWrapper<TemplateFrame> wrapper = new EntityWrapper<>();
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setDelMark(Const.DEL_FLAG_NORMAL);
        templateFrame.setCType("TENANT");
        templateFrame.setTenantID(context.getTenantId().intValue());
        wrapper.setEntity(templateFrame);
        List<TemplateFrame> templateFrames = templateFrameMapper.selectList(wrapper);
        for (TemplateFrame frame : templateFrames) {
            if (frame.getSActive() == Const.DEL_FLAG_DEL) {
                frame.setSActive(Const.DEL_FLAG_NORMAL);
                templateFrameMapper.updateById(frame);
            }
        }
        TemplateFrame frame = templateFrameMapper.selectById(id);
        MicroApp microApp = iMicroAppService.MicroApp(context.getTenantId().intValue());
        if (ToolUtil.isEmpty(microApp)){
            throw new GunsException("当前租户下面没有授权小程序，请先授权后在启用模板！！！");
        }
        if (ToolUtil.isNotEmpty(frame)) {
            if (ToolUtil.isNotEmpty(frame.getSMicroAppID())){
                frame.setSActive(Const.DEL_FLAG_DEL);
                Integer integer = templateFrameMapper.updateById(frame);
                MicroApp microAppInfo = iMicroAppService.getMicroAppInfo(frame.getSMicroAppID());
                Map<String, Object> map = new HashMap<>();
                map.put("extEnable", "true");
                map.put("extAppid", frame.getSMicroAppID());
                wxAuthorService.Commit(frame.getIMicroTempID().toString(), JsonUtil.mapToJsonStr(map), "1.0", "test", microAppInfo.getAuthorizerAccessToken());
                return integer;
            }else {
                frame.setSActive(Const.DEL_FLAG_DEL);
                frame.setSMicroAppID(microApp.getAppId());
                Integer integer = templateFrameMapper.updateById(frame);
                MicroApp microAppInfo = iMicroAppService.getMicroAppInfo(frame.getSMicroAppID());
                Map<String, Object> map = new HashMap<>();
                map.put("extEnable", "true");
                map.put("extAppid", frame.getSMicroAppID());
                wxAuthorService.Commit(frame.getIMicroTempID().toString(), JsonUtil.mapToJsonStr(map), "1.0", "test", microAppInfo.getAuthorizerAccessToken());
                return integer;
            }
        } else {
            throw new GunsException("模板Id有误！！！");
        }
    }

    @Override
    public List<TemplateFrame> getTemplateList(int tenantId) {
        EntityWrapper<TemplateFrame> wrapper = new EntityWrapper<>();
        TemplateFrame templateFrame = new TemplateFrame();
        templateFrame.setDelMark(Const.DEL_FLAG_NORMAL);
        templateFrame.setTenantID(tenantId);
        wrapper.setEntity(templateFrame);
        List<TemplateFrame> templateFrames = templateFrameMapper.selectList(wrapper);
        return templateFrames;
    }


    public Map<String, Object> isResultMap(List list, SearchCriteriaBase searchCriteriaBase) {
        Map<String, Object> map = new HashMap<>();
        map.put("count", list.size());
        map.put("limit", searchCriteriaBase.getLimit());
        map.put("pageIndex", searchCriteriaBase.getPageIndex());
        map.put("hasMore", false);
        map.put("items", list);
        return map;
    }
}
